<template>
  <el-dialog title="添加权限" :visible="showDialog" width="50%" @close="onClose" @closed="onClosed">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="form.code"></el-input>
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="form.description"></el-input>
      </el-form-item>
      <el-form-item label="权限状态" prop="enVisible">
        <el-switch v-model="form.enVisible" active-text="启用" inactive-text="禁用" active-value="1" inactive-value="0">
        </el-switch>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="onClose">取 消</el-button>
      <el-button type="primary" size="mini" @click="onConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addPerAPI } from '@/api/permission.js'
export default {
  name: 'AddPer',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    type: {
      type: [Number, String],
      required: true
    },
    pid: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: '',
        type: '',
        code: '',
        description: '',
        pid: '',
        enVisible: ''
      },
      formRules: {
        enVisible: [{ required: true, message: '权限状态是必选项', trigger: 'change' }],
        name: [{ required: true, message: '权限名称是必填项', trigger: 'blur' }],
        code: [{ required: true, message: '权限标识是必填项', trigger: 'blur' }],
        description: [{ required: true, message: '权限描述是必填项', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 对话框关闭前的回调
    onClose() {
      this.$emit('update:showDialog', false)
    },
    // 对话框关闭完成后的回调
    onClosed() {
      // 主要清理数据
      this.$emit('update:type', '')
      this.$emit('update:pid', '')
      this.$refs.formRef.resetFields()
    },
    // 点击了确认按钮
    onConfirm() {
      // 表单效验
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        // 整理数据
        const form = { ...this.form, pid: this.pid, type: this.type }
        // console.log(form)
        await addPerAPI(form)
        this.$message.success('添加成功')
        this.$emit('reload')
        this.$emit('update:showDialog', false)
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
